<?php

namespace app\common\model;

use think\Model;

class PermissionModel extends Model
{
    //
    protected $table = 'sys_permission';


    /**
     * @param $username
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public function get_login_user_permissions($username)
    {
        $permissions = session('loginUserPermissions');
        if ($permissions != null) {
            return $permissions;
        }
        $user_model = \model('UserModel');
        $users = $user_model->where('name', $username)->select();
        if (count($users) < 1 || count($users) > 1) {
            return array('ok'=>'1');
        }

        //角色ID
        $user_role_id = $users[0]->role_id;

        //权限
        $ps_model = \model('PermissionModel');
        $ps = $ps_model->where('role_id', '=', $user_role_id)->select();
        if (count($ps) < 1) {
            return array('ok'=>'2');
        }
        $ps_menu_ids = array();

        for ($i = 0; $i < count($ps); $i++) {
            $ps_menu_ids[$i] = $ps[$i]->menu_id;
        }

        $menu_model = \model('MenuModel');
        $menus = $menu_model->where('id', 'in', $ps_menu_ids)->select();
        for ($i = 0; $i < count($menus); $i++) {
            $permissions[$i] = '/'.$menus[$i]->module_name.'/'.$menus[$i]->action_name.'/'.$menus[$i]->function_name;
        }
        session('loginUserPermissions',$permissions);
        return $permissions;
    }
}
